﻿// Write a program that reads a positive integer number N (N < 20) 
// from console and outputs in the console the numbers 1 ... N numbers arranged as a spiral.

using System;

class SpiralOfNumbers
{
    static void Main()
    {
        Console.Write("Enter N: ");
        int n = int.Parse(Console.ReadLine());

        int direction = 1; //1 = left; 2 = down; 3 = right; 4 = up

        int maxY = n - 1;
        int minY = 0;

        int maxX = n - 1;
        int minX = 1;

        int coordX = 0, coordY = 0;

        int[,] resultMatrix = new int[n, n];

        for (int i = 1; i <= n * n; i++)
        {
            resultMatrix[coordX, coordY] = i;

            //update coordinates
            switch (direction)
            {
                case 1:
                    {
                        if (coordY < maxY)
                        {
                            coordY++;
                        }
                        else
                        {
                            direction = 2;
                            maxY--;
                            coordX++;
                        }
                        break;
                    }
                case 2:
                    {
                        if (coordX < maxX)
                        {
                            coordX++;
                        }
                        else
                        {
                            direction = 3;
                            maxX--;
                            coordY--;
                        }
                        break;
                    }
                case 3:
                    {
                        if (coordY > minY)
                        {
                            coordY--;
                        }
                        else
                        {
                            direction = 4;
                            minY++;
                            coordX--;
                        }
                        break;
                    }
                case 4:
                    {
                        if (coordX > minX)
                        {
                            coordX--;
                        }
                        else
                        {
                            direction = 1;
                            minX++;
                            coordY++;
                        }
                        break;
                    }
            }
        }
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                Console.Write("{0:D3} ", resultMatrix[i , j]);
            }
            Console.WriteLine();
        }
    }
}
